package com.lxq.LeetCode.search;

import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        int[] nums = {0, 1, 2};
        System.out.println(search(nums, 1));
    }

    public static int search(int[] nums, int target) {
        if (nums.length == 1) {
            return nums[0] == target ? 0 : -1;
        }
        if (nums.length == 2) {
            if (nums[0] == target || nums[1] == target) {
                return nums[0] == target ? 0 : 1;
            } else {
                return -1;
            }
        }
        int res = -1;
        int[] originNums = new int[nums.length];
        int k = -1;
        //确定翻转位k
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] > nums[i + 1]) {
                k = nums.length - i - 1;
                break;
            }
        }
        if (k >= 0) {
            //还原有序数列
            for (int i = 0, j = nums.length - k; i < k; i++, j++) {
                originNums[i] = nums[j];
            }
            for (int i = k, j = 0; i < originNums.length; i++, j++) {
                originNums[i] = nums[j];
            }
            res = Arrays.binarySearch(originNums, target);

            return res < 0 ? -1 : (res < k ? res + (nums.length - k) : res - k);
        } else {
            res = Arrays.binarySearch(nums, target);

            return res < 0 ? -1 : res;
        }
    }
}
